import time

from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from autoTest_ecshop.utils.log_util import logger
class Base():
    def __init__(self,driver):
        self.driver =driver
    ##查找单个元素
    def find_element(self,locator):
        try:
            logger.info(f"查找元素{locator}")
            return WebDriverWait(self.driver,5).\
                until(EC.visibility_of_element_located(locator))
        except Exception as e:
            logger.error(f"元素 {locator} 定位失败。失败原因是：\n {e}")

    ##查找多个元素
    def find_elements(self, locator):
        try:
            logger.info(f"查找元素{locator}")
            return WebDriverWait(self.driver, 5).\
                until(EC.visibility_of_element_located(locator))
        except Exception as e:
            logger.error(f"元素 {locator} 定位失败。失败原因是：\n {e}")

    ## 输入数据
    def input_data(self,locator,keywords):
        ###查找元素
        element = self.find_element(locator)
        ### 清空输入框内容
        element.clear()
        ### 输入数据
        logger.info(f"输入数据：{keywords}")
        element.send_keys(keywords)

    def clickBtn(self,locator):
        #查找元素
        button=self.find_element(locator)
        #点击
        button.click()
        time.sleep(1)

    def switchAlert(self,keywords=None,text=True,action=True):
        try:
            #切换到警告框
            alert=self.driver.switch_to.alert
            #输入信息
            if keywords:
                alert.send_keys(keywords)
            #获取文本信息
            if text:
                text= alert.text
            #点击确认按钮
            if action:
                alert.accept()
            #点击取消按钮
            else:
                alert.dismiss()
            ###返回文本信息
            if text:
                logger.info(f"返回信息是：{text}")
                return text
        except Exception as e:
            logger.error(f"错误信息是：\n{e}")

    def get_text(self,locator):
        # 查找元素
        element = self.find_element(locator)
        # 获取文本信息
        text = element.text
        logger.info(f"获取到的文本信息是：{text}")
        return text
